package com.mall.util;

import com.mall.db.domain.Member;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆拦截，拦截未登陆的用户
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 未执行之前的拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //返回false表示拦截成功回到登陆界面，true表示登陆信息存在不做拦截
        HttpSession session = request.getSession();
        Member m = (Member) session.getAttribute("member");//默认有效时间为30分钟
        if(StringUtils.isEmpty(m)){
            String alert = "<script>" +
                    "alert('登陆信息已过期，请重新登陆!');" +
                    "parent.location.href= '"+request.getContextPath()+"/login'" +
                    "</script>";
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(alert);
            //重定向到登陆界面
            //request.getRequestDispatcher("/login").forward(request,response);
            return false;
        }
        return true;
    }
}
